import mongoose, { Document, Schema } from 'mongoose'
import dayjs from 'dayjs'
import { Counter } from './counter'

export interface IArticle extends Document {
  id: number
  title: string
  content: string
  tags: string[]
  sort_order: number
  status: number // 0:未发布 1:已发布
  category_id: number[]
  view_count: number
  created_by: number | null
  updated_by: number | null
  created_at: string
  updated_at: string
}

const ArticleSchema: Schema = new Schema({
  id: {
    type: Number,
    unique: true,
    description: '文章id'
  },
  title: {
    type: String,
    unique: true,
    required: true,
    description: '标题'
  },
  content: {
    type: String,
    required: true,
    description: '内容'
  },
  tags: {
    type: [String],
    default: [],
    description: '标签'
  },
  sort_order: {
    type: Number,
    default: 0,
    description: '排序号，值越小越靠前'
  },
  status: {
    type: Number,
    default: 0,
    description: '状态，0:未发布 1:已发布'
  },
  category_id: {
    type: [Number],
    required: true,
    description: '分类id'
  },
  view_count: {
    type: Number,
    default: 0,
    description: '浏览量'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  },
  created_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  }
})

// 保存前处理
ArticleSchema.pre<IArticle>('save', async function (next) {
  if (this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'article_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      )
      this.id = counter.seq
      next()
    } catch (error: any) {
      next(error)
    }
  } else {
    next()
  }
})

// 更新时更新时间戳
ArticleSchema.pre<IArticle>('findOneAndUpdate', function (next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') })
  next()
})

// 配置 toJSON 输出
ArticleSchema.set('toJSON', {
  transform: function (doc, ret) {
    const { _id, __v, ...rest } = ret
    return rest
  }
})

export const Article = mongoose.model<IArticle>(
  'article',
  ArticleSchema,
  'article'
)
